﻿using B.MESUI.Login.BasicData_UI.BasicData;
using B.MESUI.Login.BasicData_UI.BasicData.Select;
using B.MESUI.Login.BasicData_UI.Customer;
using B.MESUI.Login.Properties;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace B.MESUI.Login.BasicData_UI.Material
{
    public partial class GetMaterialForm : DevExpress.XtraEditors.XtraForm
    {
        private GetUserControl userControl;
        private TextEdit txtCode, txtName;
        private int pageIndex = 1, pageSize = 10, totalCount = 0;
        public FlowLayoutPanel QueryPanel { get; set; }
        public GetMaterialForm()
        {
            InitializeComponent();
            InitLayout();
            
            userControl = new GetUserControl { Dock = DockStyle.Fill };
            this.Controls.Add(userControl);

            // 指定需要的查询字段和类型
            var fields = new List<GetUserControl.QueryField>
     {
        
         new GetUserControl.QueryField { FieldName = "CUSTOMER_NAME", DisplayName = "物料名称", FieldType = GetUserControl.QueryFieldType.TextBox }
     };
            userControl.SetQueryFields(fields);

            _ = LoadData();
            // 恢复查询和分页按钮事件绑定
            userControl.btnQuery.Click += async (s, e) => { pageIndex = 1; await LoadData(); };
            userControl.btnReset.Click += async (s, e) =>
            {
                var qv = userControl.GetQueryValues();
                foreach (var k in qv.Keys.ToList())
                {
                    if (userControl.QueryControls[k] is DevExpress.XtraEditors.BaseEdit be)
                        be.EditValue = null;
                }
                pageIndex = 1;
                await LoadData();
            };
            userControl.btnPrev.Click += async (s, e) => { if (pageIndex > 1) { pageIndex--; await LoadData(); } };
            userControl.btnNext.Click += async (s, e) => { if (pageIndex < GetTotalPages()) { pageIndex++; await LoadData(); } };
            userControl.btnFirst.Click += async (s, e) => { pageIndex = 1; await LoadData(); };
            userControl.btnLast.Click += async (s, e) => { pageIndex = GetTotalPages(); await LoadData(); };
            userControl.btnJump.Click += async (s, e) =>
            {
                int jumpPage;
                if (int.TryParse(userControl.txtJump.Text, out jumpPage))
                {
                    if (jumpPage >= 1 && jumpPage <= GetTotalPages())
                    {
                        pageIndex = jumpPage;
                        await LoadData();
                    }
                }
            };
            //添加按钮点击事件
            userControl.btnAdd.Click += (s, e) =>
            {
                var addForm = new AddMaterialForm();
                addForm.OnAddMaterial += () =>
                {
                    LoadData();
                };
                addForm.ShowDialog();
            };
            //修改按钮点击事件
            userControl.btnEdit.Click += (s, e) =>
            {
                // 获取选中行
                var gridView = userControl.MainGrid.MainView as GridView;
                if (gridView != null && gridView.GetSelectedRows().Length > 0)
                {
                    var selectedRowHandle = gridView.GetSelectedRows()[0];
                    if (selectedRowHandle >= 0)
                    {
                        // 获取选中的客户数据
                        var customerDto = gridView.GetRow(selectedRowHandle) as GetMaterialDTO;
                        if (customerDto != null)
                        {
                            // 将 CustomerDTO 转换为 UpdateCustomer
                            var updateCustomer = new UpdateMaterialDTO
                            {
                                Id = customerDto.Id,
                                MaterialCode = customerDto.MaterialCode,
                                MaterialName = customerDto.MaterialName,
                                Spec = customerDto.Spec,
                                Unit = customerDto.Unit,
                                Remark = customerDto.Remark,
                              
                            };

                            // 创建编辑窗体并传递数据
                            var editForm = new EditMaterialForm(updateCustomer);
                            editForm.EditMaterialEvent += () =>
                            {
                                LoadData();
                            };
                            editForm.ShowDialog();
                        }
                    }
                }
                else
                {
                    XtraMessageBox.Show("请先选择要修改的客户记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            };

             //批量删除
     userControl.btnDelete.Click += async (s, e) =>
     {
         var gridView = userControl.MainGrid.MainView as GridView;
         if (gridView != null)
         {
             // 获取所有选中的行的ID
             List<string> selectedIds = new List<string>();

             // 获取选中的行
             int[] selectedRows = gridView.GetSelectedRows();
             if (selectedRows != null && selectedRows.Length > 0)
             {
                 foreach (int rowHandle in selectedRows)
                 {
                     if (rowHandle >= 0)
                     {
                         var MaterialDto = gridView.GetRow(rowHandle) as GetMaterialDTO;
                         if (MaterialDto != null)
                         {
                             selectedIds.Add(MaterialDto.Id);
                         }
                     }
                 }
             }
             else
             {
                 // 如果没有通过 GetSelectedRows 获取到选中行，则尝试通过复选框获取
                 for (int i = 0; i < gridView.RowCount; i++)
                 {
                     bool isChecked = false;
                     try
                     {
                         isChecked = Convert.ToBoolean(gridView.GetRowCellValue(i, "CheckboxColumn"));
                     }
                     catch
                     {
                         // 忽略转换错误
                         continue;
                     }

                     if (isChecked)
                     {
                         var MaterialDto = gridView.GetRow(i) as GetMaterialDTO;
                         if (MaterialDto != null)
                         {
                             selectedIds.Add(MaterialDto.Id);
                         }
                     }
                 }
             }

             // 如果没有选中任何行，提示用户
             if (selectedIds.Count == 0)
             {
                 XtraMessageBox.Show("请至少选择一条记录进行删除！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                 return;
             }

             // 确认删除
             if (XtraMessageBox.Show($"确定要删除选中的 {selectedIds.Count} 条记录吗？", "确认删除",
                 MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
             {
                 try
                 {
                     // 构建请求URL
                     string url = $"http://localhost:5198/api/Material/Delete";

                     // 将ID列表转换为逗号分隔的字符串
                     string idsString = string.Join(",", selectedIds);

                     // 添加查询参数
                     url += "?Ids=" + System.Web.HttpUtility.UrlEncode(idsString);

                     // 发送DELETE请求
                     string result = await BaseMethod.MethodsURL("delete", url);

                     // 解析返回结果
                     var apiResult = JsonConvert.DeserializeObject<dynamic>(result);

                     // 检查返回码
                     if (apiResult != null && apiResult.code.ToString() == "200")
                     {
                         XtraMessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                         LoadData(); // 刷新数据
                     }
                     else
                     {
                         string errorMsg = apiResult?.message?.ToString() ?? "未知错误";
                         XtraMessageBox.Show($"删除失败：{errorMsg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                         LoadData(); // 即使失败也刷新数据，确保UI状态正确
                     }
                 }
                 catch (Exception ex)
                 {
                     XtraMessageBox.Show($"删除失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                     LoadData(); // 发生异常时也刷新数据
                 }
             }
         }
     };

        }
        //显示
        private int GetTotalPages() => (int)Math.Ceiling((double)totalCount / pageSize);
        /// <summary>
        /// 客户显示
        /// </summary>
        /// <returns></returns>
        private async Task LoadData()
        {
            string url = $"http://localhost:5198/api/Material/GetMaterial";
            var paramList = new List<string>
       {
           $"PageIndex={pageIndex}",
           $"PageSize={pageSize}"
       };
            var queryValues = userControl.GetQueryValues();
            if (queryValues.ContainsKey("MaterialName") && !string.IsNullOrWhiteSpace(queryValues["MaterialName"]?.ToString()))
                paramList.Add($"MaterialName={queryValues["MaterialName"].ToString().Trim()}");
            
            url += "?" + string.Join("&", paramList);

            using (HttpClient client = new HttpClient())
            {
                var resp = await client.GetAsync(url);
                string json = await resp.Content.ReadAsStringAsync();
                var jobj = JObject.Parse(json);
                totalCount = jobj["totalCount"]?.Value<int>() ?? 0;
                var pageList = jobj["pageDatas"] as JArray;
                var dataList = new List<GetMaterialDTO>();
                if (pageList != null)
                {
                    foreach (var item in pageList)
                    {
                        dataList.Add(item.ToObject<GetMaterialDTO>());
                    }
                }
                // 先绑定数据源
                var gridControl = userControl.MainGrid;
                if (gridControl != null)
                {
                    gridControl.DataSource = dataList;

                    var gridView = gridControl.MainView as GridView;
                    if (gridView != null)
                    {
                        // 添加复选框列
                        if (gridView.Columns["CheckboxColumn"] == null)
                        {
                            // 设置选择模式为多选
                            gridView.OptionsSelection.MultiSelect = true;
                            gridView.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;

                            // 添加行点击事件，确保点击行时不会取消其他行的选择
                            gridView.Click += (s, e) =>
                            {
                                DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hitInfo = gridView.CalcHitInfo((e as MouseEventArgs).Location);
                                if (hitInfo.InRow && !(hitInfo.Column != null && hitInfo.Column.FieldName == "CheckboxColumn"))
                                {
                                    // 如果点击的是行而不是复选框列，则切换该行的复选框状态
                                    bool currentValue = Convert.ToBoolean(gridView.GetRowCellValue(hitInfo.RowHandle, "CheckboxColumn"));
                                    gridView.SetRowCellValue(hitInfo.RowHandle, "CheckboxColumn", !currentValue);
                                }
                            };
                        }
                        // 设置表头
                        if (gridView.Columns["Id"] != null)
                            gridView.Columns["Id"].Caption = "物料s编号";
                        if (gridView.Columns["MaterialCode"] != null)
                            gridView.Columns["MaterialCode"].Caption = "物料编码";
                        if (gridView.Columns["MaterialName"] != null)
                            gridView.Columns["MaterialName"].Caption = "物料名称";
                        if (gridView.Columns["Spec"] != null)
                            gridView.Columns["Spec"].Caption = "规格";
                        if (gridView.Columns["Unit"] != null)
                            gridView.Columns["Unit"].Caption = "单位";
                        if (gridView.Columns["Remark"] != null)
                            gridView.Columns["Remark"].Caption = "备注";
                        if (gridView.Columns["CreatedBy"] != null)
                            gridView.Columns["CreatedBy"].Caption = "创建人";
                        if (gridView.Columns["CreatedAt"] != null)
                            gridView.Columns["CreatedAt"].Caption = "创建时间";
                        if (gridView.Columns["UpdatedBy"] != null)
                            gridView.Columns["UpdatedBy"].Caption = "修改人";
                       
                        if (gridView.Columns["UpdatedAt"] != null)
                            gridView.Columns["UpdatedAt"].Caption = "修改时间";
                        // 可继续添加其他字段
                    }
                    // 优化中间表格区显示
                    gridControl.Dock = DockStyle.Fill;
                    gridView.OptionsView.ColumnAutoWidth = false; // 允许自定义列宽
                    gridView.BestFitColumns(); // 自动适应内容宽度
                    foreach (DevExpress.XtraGrid.Columns.GridColumn col in gridView.Columns)
                    {
                        col.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; // 表头居中
                        col.AppearanceHeader.Font = new System.Drawing.Font("Tahoma", 10, System.Drawing.FontStyle.Bold); // 表头加粗
                        col.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; // 内容居中、
                    }
                    // 显示行号
                    gridView.IndicatorWidth = 40;
                    gridView.CustomDrawRowIndicator += (s, e) =>
                    {
                        if (e.Info.IsRowIndicator && e.RowHandle >= 0)
                        {
                            e.Info.DisplayText = (e.RowHandle + 1).ToString();
                        }
                    };

                }
                //调试
                if (userControl.MainGrid != null)
                    userControl.MainGrid.DataSource = dataList;
                userControl.lblPageInfo.Text = $"第{pageIndex}/{(GetTotalPages() == 0 ? 1 : GetTotalPages())}页 共{totalCount}条";
            }
        }

    }
}
